package com.qfedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.dao.UserMapper;
import com.qfedu.service.MyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0
 * 公众号：Java架构栈
 * @Author: 卓不凡
 */
//使用security认证的业务类 必须实现UserDetailsService,重写loadUserByUsername方法
@Service
public class MyUserServiceImpl extends ServiceImpl<UserMapper,com.qfedu.model.User> implements MyUserService,UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    //根据用户名去查找用户信息
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //GrantedAuthority 权限类，用来描述用户的角色和权限
        List<GrantedAuthority> list = new ArrayList<>();
       /* //将来这个方法一定是连接数据库查询
        if ("admin".equals(username)){//验证成功返回用户
            String encode = passwordEncoder.encode("123");
            return new User(username,encode,list);
        }
        System.out.println("用户名不存在");
        return null;*/
        QueryWrapper<com.qfedu.model.User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",username);
        com.qfedu.model.User user = this.baseMapper.selectOne(queryWrapper);
        if (user!=null){
            //添加角色
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_xiaozhang"); //创建角色信息
            list.add(authority);
            SimpleGrantedAuthority authority1 = new SimpleGrantedAuthority("ROLE_jiangshi"); //创建角色信息
            list.add(authority1);
            //用户存在
            return new User(username,user.getPassword(),list);
        }
        System.out.println("用户名不存在");
        return null;

    }
}
